#!/bin/bash

# JWT Key Generator Script for Gin Framework
# Generates a secure random JWT secret key

echo "=== JWT Secret Key Generator ==="
echo ""

# Generate a secure 64-character random key
JWT_KEY=$(openssl rand -hex 32)

echo "Generated JWT Secret Key:"
echo "JWT_SECRET_KEY=$JWT_KEY"
echo ""

# Check if .env file exists
if [ -f ".env" ]; then
    echo "Found .env file. Do you want to update it? (y/n)"
    read -r response
    if [[ "$response" =~ ^[Yy]$ ]]; then
        # Update .env file
        if grep -q "JWT_SECRET_KEY=" .env; then
            # Replace existing key
            sed -i.bak "s/JWT_SECRET_KEY=.*/JWT_SECRET_KEY=$JWT_KEY/" .env
            echo "Updated JWT_SECRET_KEY in .env file"
        else
            # Add new key
            echo "JWT_SECRET_KEY=$JWT_KEY" >> .env
            echo "Added JWT_SECRET_KEY to .env file"
        fi
    fi
else
    echo "No .env file found. Creating one from .env.example..."
    if [ -f ".env.example" ]; then
        cp .env.example .env
        sed -i.bak "s/JWT_SECRET_KEY=.*/JWT_SECRET_KEY=$JWT_KEY/" .env
        echo "Created .env file with generated JWT key"
    else
        echo "JWT_SECRET_KEY=$JWT_KEY" > .env
        echo "Created new .env file with JWT key"
    fi
fi

echo ""
echo "=== Security Notes ==="
echo "1. Keep this key secure and never commit it to version control"
echo "2. Use different keys for development and production"
echo "3. Rotate keys periodically for better security"
echo "4. Set GIN_MODE=release for production environments"
echo ""
echo "To use this key, either:"
echo "  - Export it: export JWT_SECRET_KEY=\"$JWT_KEY\""
echo "  - Or source the .env file in your deployment"